<template>
  <div class="app-container put-in-store">
    <el-form ref="form" :model="form" :rules="rules" label-width="90px" style="width:100%">
      <div style="width: 600px;" class="put-in-store">
        <el-form-item label="车辆ID" prop="bicycleId">
          <el-input v-model="form.bicycleId" ref="bicycleId" :disabled="disabled" @change="OnchangeID"
            @focus="getFocus('bicycleId')"></el-input>
        </el-form-item>
        <el-form-item label="工单号" prop="orderId">
          <el-input v-model="form.orderId" ref="orderId" disabled
            @keyup.enter.native="nextGetFocus('controllerId')"></el-input>
        </el-form-item>
        <el-form-item label="控制器号" prop="controllerId">
          <el-input v-model="form.controllerId" ref="controllerId" :disabled="components"
            @keyup.enter.native="submitForm(form)" @focus="getFocus('controllerId')"></el-input>
        </el-form-item>
        <div v-for="(item, index) in fittings" :key="index">
          <el-form-item :label="item.fittingName" :prop="item.fittingFabienName">
            <el-input v-model="form.map[item.fittingFabienName]" :disabled="operation" :ref="item.fittingFabienName"
              @keyup.enter.native="nextGetFocus(index, item.fittingFabienName)"
              @focus="getFocus(item.fittingFabienName)"></el-input>
          </el-form-item>
        </div>
        <!-- <el-form-item label="车架号" prop="frameId">
          <el-input v-model="form.frameId" ref="frameId" :disabled="operation"
            @keyup.enter.native="nextGetFocus('motorId', 'frameId')" @focus="getFocus('frameId')"></el-input>
        </el-form-item>
        <el-form-item label="电机号" prop="motorId">
          <el-input v-model="form.motorId" ref="motorId" :disabled="operation"
            @keyup.enter.native="nextGetFocus('batteryId')" @focus="getFocus('motorId')"></el-input>
        </el-form-item>
        <el-form-item label="电池号" prop="batteryId">
          <el-input v-model="form.batteryId" ref="batteryId" :disabled="operation"
            @keyup.enter.native="nextGetFocus('meterId')" @focus="getFocus('batteryId')"></el-input>
        </el-form-item>
        可添加回车提交表单事件
        <el-form-item label="仪表号" prop="meterId">
          <el-input v-model="form.meterId" ref="meterId" :disabled="operation"
            @keyup.enter.native="submitForm(form)"></el-input>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm(form)">保存</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item> -->
      </div>
      <!-- <div class="calculator">
        <calculator />
      </div> -->
      <!-- 虚拟键盘输入 -->
      <div class="keyword">
        <el-button @click="getResult('1')">1</el-button>
        <el-button @click="getResult('2')">2</el-button>
        <el-button @click="getResult('3')">3</el-button>
        <el-button @click="getResult('4')">4</el-button>
        <el-button @click="getResult('5')">5</el-button>
        <el-button @click="getResult('6')">6</el-button>
        <el-button @click="getResult('7')">7</el-button>
        <el-button @click="getResult('8')">8</el-button>
        <el-button @click="getResult('9')">9</el-button>
        <el-button @click="getResult('A')">A</el-button>
        <el-button @click="getResult('B')">B</el-button>
        <el-button @click="getResult('C')">C</el-button>
        <el-button @click="getResult('-')">-</el-button>
        <el-button @click="getResult('0')">0</el-button>
        <el-button @click="getResult('_')">_</el-button>
        <el-button @click="getResult('.')">.</el-button>
        <el-button @click="getResult('del')">删除</el-button>
        <el-button @click="getResult('clear')">清空</el-button>
        <el-button @click="submitFormaaa(form)">保存</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </el-form>

  </div>
</template>

<script>
import { getBicycle, updateBicycle, selectTicketsclose, selectFitting, selectFittings } from "@/api/storage/controller/bicycle";

function throttle(func, delay) {
  let lastCall = 0;
  return function (...args) {
    const now = new Date().getTime();
    if (now - lastCall < delay) {
      return;
    }
    lastCall = now;
    return func.apply(this, args);
  }
}
export default {
  name: "Gather",
  dicts: ["accessory_type"],
  data() {
    return {
      disabled: false,
      components: "",
      operation: "",
      classOption: "",
      focusVaule: "",
      //配件数组
      fittings: [],
      form: {
        bicycleId: "",
        controllerId: "",
        map: {
        },
        orderId: "",
        orderFlag: null,
        controllerFlag: null
      },
      rules: {
        bicycleId: [
          { required: true, message: '请录入正确车辆ID', trigger: 'blur' }
        ],

      }
    }
  },

  mounted() {
    selectFittings().then(res => {
      this.fittings = res.data
      this.fittings = this.fittings.filter(item => item.delFlag == 0);
      console.log(this.fittings);
    })
    this.submitFormaaa = throttle(this.submitForm, 1000);
    if (this.$route.query.res === "2") {
      this.components = true
      this.operation = false
      this.$refs.bicycleId.$el.addEventListener('keyup', (event) => {
        if (event.keyCode === 13) {
          this.$refs[this.fittings[0].fittingFabienName][0].focus()
        }
      });
    } else {
      this.components = false
      this.operation = true
      this.$set(this.rules, "controllerId", [
        { required: true, message: '请录入控制器号', trigger: 'blur' }
      ])
      this.$refs.bicycleId.$el.addEventListener('keyup', (event) => {
        if (event.keyCode === 13) {
          this.$refs.controllerId.focus()
        }
      });
    }
    if (this.$route.params.bicycleId) {
      getBicycle(this.$route.params.bicycleId).then(response => {
        this.form = response.data;
      });
      this.$refs.controllerId.focus()
      this.disabled = true;
    }
    this.$refs.bicycleId.focus()
    this.getDicts("accessory_type").then(res => {
      this.classOption = res.data
    })
    // setTimeout(() => {
    //   document.activeElement.innerText = "1"
    // }, 1000)

  },
  beforeDestroy() {
    // 清理可能存在的定时器或事件监听器，避免内存泄漏
    this.submitFormaaa = null;
  },
  methods: {

    throttle(func, delay) {
      let lastCall = 0;
      return function (...args) {
        const now = new Date().getTime();
        if (now - lastCall < delay) {
          return;
        }
        lastCall = now;
        return func.apply(this, args);
      }
    },
    //下一个输入框获取焦点
    nextGetFocus(nextRef, thisRef) {
      if (nextRef != this.fittings.length - 1) {
        this.$refs[this.fittings[nextRef + 1].fittingFabienName][0].focus()
        let data = {};
        this.classOption.map(item => {
          if (item.dictValue == thisRef) {
            data = {
              accessoryType: item.dictValue,
              data: this.form.map[thisRef]
            }
          }
        })
        selectFitting(data).then(response => {
          if (response.code == 200) {
            this.speak("扫描成功");
          } else {
            this.speak("扫描失败");
          }
        }
        )
      } else {
        this.submitForm(this.form)
      }

    },
    //语音提示
    speak(text) {
      const msg = new SpeechSynthesisUtterance(text);
      window.speechSynthesis.speak(msg);
    },
    //虚拟键盘输入
    getResult(e) {
      if (this.focusVaule && this.focusVaule == "bicycleId") {
        this.$refs.bicycleId.focus()
        if (e == "del") {
          this.form.bicycleId = this.form.bicycleId.slice(0, this.form.bicycleId.length - 1);
          return;
        } else if (e == "clear") {
          this.form.bicycleId = ""
          return;
        }
        this.form.bicycleId += e
      } else {
        this.$refs[this.focusVaule][0].focus()
        if (e == "del") {
          this.form.map[this.focusVaule] = this.form.map[this.focusVaule].slice(0, this.form.map[this.focusVaule].length - 1);
          return;
        } else if (e == "clear") {
          this.form.map[this.focusVaule] = ""
          return;
        }
        this.form.map[this.focusVaule] += e
      }
    },
    getFocus(res) {
      this.focusVaule = res
    },
    //保存表单
    submitForm(formName) {
      let accessoryDataVos = []
      if (this.$route.query.res === "2") {
        this.form.orderFlag = 2
        this.fittings.map(item => {
          let AccessoryDataVo = {
            fittingId: item.fittingId,
            accessoryType: item.fittingFabienName,
            data: formName.map[item.fittingFabienName]
          }
          accessoryDataVos.push(AccessoryDataVo)
        })
      } else {
        this.form.controllerFlag = 2
        accessoryDataVos = [{
          accessoryType: "controllerId",
          data: formName.controllerId
        }
        ]
      }
      this.$set(formName, "accessoryDataVos", accessoryDataVos)
      console.log(formName);
      updateBicycle(formName).then(response => {
        if (response.code == 200) {
          if (this.$route.params.bicycleId) {
            this.$modal.msgSuccess("修改成功")
            // 关闭当前tabs
            this.$store.dispatch('tagsView/delView', this.$route);
            if (this.$route.query.res === "2") {
              // 跳转路由
              this.$router.replace({ path: '/storage/operation' });
            } else {
              // 跳转路由
              this.$router.replace({ path: '/storage/bicycle' });
            }
            // window.history.go(-1)
          } else {
            this.speak("扫描成功")
            this.$modal.msgSuccess("添加成功")
          }
        } else {
          this.$refs.msgerror(response.msg);
        }
      });
      this.reset();
    },

    OnchangeID(e) {
      this.reset()
      getBicycle(e).then(response => {
        this.form = response.data;
        selectTicketsclose(response.data.orderId).then(response => {
          if (response.code != 200) {
            this.$refs.msgerror("车辆ID相关订单已结案")
          }
        })
      });
    },
    reset() {
      this.form.controllerId = "";
      this.form.bicycleId = "";
      this.form.map = "";
      this.resetForm("form");
    }
  }
}
</script>

<style scoped lang="scss">
.put-in-store {
  // display: flex;
  justify-content: center;

}



calculator {
  width: 100px;
  height: 200px;
}

.el-form {
  display: flex;
}

.keyword {
  width: 320px;
  margin: 0 auto;
  // width: 190px;
  display: grid;
  border: solid 1px #eee;
  padding: 6px;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  gap: 3px;
  border-radius: 4px;
  background-color: hsla(242, 88%, 60%, 0.621);
  font-weight: bold;
  color: #888;
}

.keyword .el-button {
  margin: 0 !important;
  padding: 10px;
  // font-weight: 600;
  width: 100%;
  font-size: 25px;
}

// .el-input__inner {
//   font-size: 100px;
// }
</style>
